<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="订单号/用户名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.status" placeholder="订单状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="filter-item"
        value-format="yyyy-MM-dd"
        @change="handleDateChange"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleExport"
      >
        导出订单
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="订单号" prop="orderNo" align="center" width="180" />
      <el-table-column label="用户信息" align="center" width="150">
        <template slot-scope="{row}">
          <div>{{ row.userName }}</div>
          <div>{{ row.userPhone }}</div>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" width="120" align="center">
        <template slot-scope="{row}">
          <span>¥ {{ row.totalAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag size="small">
            {{ row.paymentMethod === 1 ? '微信支付' : row.paymentMethod === 2 ? '支付宝' : '其他' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.statusText }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" width="180" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleDetail(row)">
            详情
          </el-button>
          <el-button 
            v-if="row.status === 1" 
            size="mini" 
            type="success" 
            @click="handleShip(row)"
          >
            发货
          </el-button>
          <el-button 
            v-if="row.status === 4" 
            size="mini" 
            type="warning" 
            @click="handleRefund(row)"
          >
            退款
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 订单详情弹窗 -->
    <el-dialog title="订单详情" :visible.sync="detailDialogVisible" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="currentOrder.status | statusFilter">
            {{ currentOrder.statusText }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="收货人">{{ currentOrder.receiverName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.receiverPhone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.receiverAddress }}</el-descriptions-item>
        <el-descriptions-item label="订单备注" :span="2">{{ currentOrder.remark || '-' }}</el-descriptions-item>
      </el-descriptions>

      <el-table :data="currentOrder.items" border style="margin-top: 20px">
        <el-table-column label="商品图片" width="100" align="center">
          <template slot-scope="{row}">
            <el-image 
              style="width: 50px; height: 50px"
              :src="row.productImage"
              :preview-src-list="[row.productImage]"
            />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="productName" />
        <el-table-column label="规格" prop="productSpec" width="100" align="center" />
        <el-table-column label="单价" width="100" align="center">
          <template slot-scope="{row}">¥ {{ row.price }}</template>
        </el-table-column>
        <el-table-column label="数量" width="100" align="center" prop="quantity" />
        <el-table-column label="小计" width="100" align="center">
          <template slot-scope="{row}">¥ {{ row.price * row.quantity }}</template>
        </el-table-column>
      </el-table>

      <div class="order-amount" style="margin-top: 20px; text-align: right">
        <p>商品总额：¥ {{ currentOrder.goodsAmount }}</p>
        <p>运费：¥ {{ currentOrder.freightAmount }}</p>
        <p>优惠金额：¥ {{ currentOrder.discountAmount }}</p>
        <p class="total">实付金额：¥ {{ currentOrder.totalAmount }}</p>
      </div>
    </el-dialog>

    <!-- 发货弹窗 -->
    <el-dialog title="订单发货" :visible.sync="shipDialogVisible">
      <el-form
        ref="shipForm"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="物流公司" prop="company">
          <el-select v-model="shipForm.company" placeholder="请选择物流公司">
            <el-option
              v-for="item in logisticsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="shipForm.trackingNo" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip">确认发货</el-button>
      </div>
    </el-dialog>

    <!-- 退款弹窗 -->
    <el-dialog title="退款处理" :visible.sync="refundDialogVisible">
      <el-form
        ref="refundForm"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="退款金额">
          <span>¥ {{ refundForm.amount }}</span>
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          <el-input v-model="refundForm.reason" type="textarea" :rows="2" disabled />
        </el-form-item>
        <el-form-item label="处理结果" prop="status">
          <el-radio-group v-model="refundForm.status">
            <el-radio :label="1">同意退款</el-radio>
            <el-radio :label="2">拒绝退款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input v-model="refundForm.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList, getOrderDetail, shipOrder, handleRefund, exportOrders } from '@/api/order'
import { Pagination } from 'element-ui'
import { parseTime } from '@/utils'

export default {
  name: 'OrderList',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'info',    // 待付款
        1: 'warning', // 待发货
        2: 'primary', // 已发货
        3: 'success', // 已完成
        4: 'danger',  // 退款中
        5: 'info'     // 已取消
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: undefined,
        status: undefined,
        startDate: undefined,
        endDate: undefined
      },
      dateRange: [],
      statusOptions: [
        { label: '待付款', value: 0 },
        { label: '待发货', value: 1 },
        { label: '已发货', value: 2 },
        { label: '已完成', value: 3 },
        { label: '退款中', value: 4 },
        { label: '已取消', value: 5 }
      ],
      logisticsOptions: [
        { label: '顺丰快递', value: 'SF' },
        { label: '圆通快递', value: 'YTO' },
        { label: '中通快递', value: 'ZTO' },
        { label: '韵达快递', value: 'YD' }
      ],
      detailDialogVisible: false,
      shipDialogVisible: false,
      refundDialogVisible: false,
      currentOrder: {},
      shipForm: {
        orderId: undefined,
        company: '',
        trackingNo: ''
      },
      shipRules: {
        company: [{ required: true, message: '请选择物流公司', trigger: 'change' }],
        trackingNo: [{ required: true, message: '请输入物流单号', trigger: 'blur' }]
      },
      refundForm: {
        orderId: undefined,
        amount: 0,
        reason: '',
        status: 1,
        remark: ''
      },
      refundRules: {
        status: [{ required: true, message: '请选择处理结果', trigger: 'change' }],
        remark: [{ required: true, message: '请输入处理备注', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getOrderList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDateChange(val) {
      this.listQuery.startDate = val ? val[0] : undefined
      this.listQuery.endDate = val ? val[1] : undefined
    },
    handleDetail(row) {
      this.detailDialogVisible = true
      getOrderDetail(row.id).then(response => {
        this.currentOrder = response.data
      })
    },
    handleShip(row) {
      this.shipDialogVisible = true
      this.shipForm.orderId = row.id
    },
    confirmShip() {
      this.$refs['shipForm'].validate((valid) => {
        if (valid) {
          shipOrder(this.shipForm).then(() => {
            this.shipDialogVisible = false
            this.$notify({
              title: '成功',
              message: '发货成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleRefund(row) {
      this.refundDialogVisible = true
      this.refundForm = {
        orderId: row.id,
        amount: row.refundAmount,
        reason: row.refundReason,
        status: 1,
        remark: ''
      }
    },
    confirmRefund() {
      this.$refs['refundForm'].validate((valid) => {
        if (valid) {
          handleRefund(this.refundForm).then(() => {
            this.refundDialogVisible = false
            this.$notify({
              title: '成功',
              message: '处理成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleExport() {
      this.$confirm('是否确认导出所有订单数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        exportOrders(this.listQuery).then(response => {
          const blob = new Blob([response.data])
          const fileName = `订单数据${parseTime(new Date(), '{y}{m}{d}')}.xlsx`
          if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
          } else {
            navigator.msSaveBlob(blob, fileName)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-amount {
  font-size: 14px;
  line-height: 1.8;
  .total {
    font-size: 16px;
    font-weight: bold;
    color: #f56c6c;
  }
}
</style> 